package schedule.vk {
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import schedule.utils.MD5;

	public class User extends EventDispatcher {
		
		public static const LAST_GROUP_RETRIEVED:String = "last_group_retrieved";

		private const UserGroupVarKey:int = 1042;
		private const Secret:String = "nevergonnagiveyouup";
		private const ApiUrl:String = "http://api.vkontakte.ru/api.php?";
				
		public function retrieveLastVisitedGroup():void
		{
			var sig:String = AppData.viewerId
				+ "api_id=" + AppData.apiId.toString()
				+ "key=" + UserGroupVarKey.toString()
				+ "method=getVariable" 
				+ "v=2.0"
				+ Secret;

			var sigHash:String = MD5.hex_md5 (sig);
			var url:String = ApiUrl
				+ "api_id=" + AppData.apiId.toString()
				+ "&method=getVariable"
				+ "&key=" + UserGroupVarKey.toString()
				+ "&v=2.0"
				+ "&sig=" + sigHash;
			
			var loader:URLLoader = new URLLoader(); 
			loader.addEventListener(Event.COMPLETE, function (e:Event):void {
				var xml:XML = new XML(e.target.data);
				dispatchEvent(new DataRetrievedEvent(xml, LAST_GROUP_RETRIEVED));				
			}); 
			loader.load(new URLRequest(url));			
		}
		
		public function setLastVisitedGroup(group:int):void {
			var sig:String = AppData.viewerId.toString()
				+ "api_id=" + AppData.apiId.toString()
				+ "key=" + UserGroupVarKey.toString()
				+ "method=putVariable"
				+ "v=2.0"
				+ "value=" + group.toString()
				+ Secret;
				
			var sigHash:String = MD5.hex_md5 (sig);
			var url:String = ApiUrl
				+ "api_id=" + AppData.apiId.toString()
				+ "&method=putVariable&key=" + UserGroupVarKey.toString()
				+ "&v=2.0"
				+ "&value=" + group.toString()
				+ "&sig=" + sigHash;				
				
			var loader:URLLoader = new URLLoader(); 
			loader.load(new URLRequest(url)); 								
		}		
	}
}